from typing import Dict, List, Optional
from sqlalchemy import or_
from werkzeug.security import generate_password_hash
from ..models.user import User
from ..extensions.extensions import db
from flask import current_app

class UserService:
    @staticmethod
    def get_user_list(page: int = 1, per_page: int = 10, keyword: Optional[str] = None) -> Dict:
        """
        获取用户列表
        :param page: 页码
        :param per_page: 每页数量
        :param keyword: 搜索关键词
        :return: 用户列表和分页信息
        """
        query = User.query.filter_by(deleted=False)
        
        # 关键词搜索
        if keyword:
            query = query.filter(
                or_(
                    User.username.like(f'%{keyword}%'),
                    User.real_name.like(f'%{keyword}%'),
                    User.email.like(f'%{keyword}%'),
                    User.mobile.like(f'%{keyword}%')
                )
            )
        
        # 分页
        pagination = query.order_by(User.created_at.desc()).paginate(
            page=page, per_page=per_page, error_out=False
        )
        
        return {
            'total': pagination.total,
            'page': page,
            'per_page': per_page,
            'items': [item.to_dict() for item in pagination.items]
        }

    @staticmethod
    def get_user_by_id(user_id: int) -> Optional[User]:
        """
        根据ID获取用户信息
        :param user_id: 用户ID
        :return: 用户对象
        """
        return User.query.filter_by(id=user_id, deleted=False).first()

    @staticmethod
    def get_user_by_username(username: str) -> Optional[User]:
        """
        根据用户名获取用户信息
        :param username: 用户名
        :return: 用户对象
        """
        return User.query.filter_by(username=username, deleted=False).first()

    @staticmethod
    def create_user(user_data: Dict) -> User:
        """
        创建用户
        :param user_data: 用户数据
        :return: 用户对象
        """
        user = User(
            username=user_data['username'],
            real_name=user_data.get('real_name'),
            email=user_data.get('email'),
            mobile=user_data.get('mobile'),
            status=user_data.get('status', True),
            dept_id=user_data.get('dept_id')
        )
        user.password_hash = user_data['password']  # 使用password_hash setter
        
        db.session.add(user)
        db.session.commit()
        return user

    @staticmethod
    def update_user(user: User, user_data: Dict) -> User:
        """
        更新用户信息
        :param user: 用户对象
        :param user_data: 更新的用户数据
        :return: 更新后的用户对象
        """
        for key, value in user_data.items():
            if key != 'password' and hasattr(user, key):
                setattr(user, key, value)
        
        db.session.commit()
        return user

    @staticmethod
    def delete_user(user: User) -> bool:
        """
        删除用户（软删除）
        :param user: 用户对象
        :return: 是否成功
        """
        user.deleted = True
        db.session.commit()
        return True

    @staticmethod
    def update_user_status(user: User, status: bool) -> User:
        """
        更新用户状态
        :param user: 用户对象
        :param status: 状态
        :return: 更新后的用户对象
        """
        user.status = status
        db.session.commit()
        return user

    @staticmethod
    def reset_password(user: User, new_password: str) -> bool:
        """
        重置用户密码
        :param user: 用户对象
        :param new_password: 新密码
        :return: 是否成功
        """
        user.password = new_password
        db.session.commit()
        return True

    @staticmethod
    def change_password(user: User, old_password: str, new_password: str) -> bool:
        """
        修改用户密码
        :param user: 用户对象
        :param old_password: 旧密码
        :param new_password: 新密码
        :return: 是否成功
        """
        if not user.verify_password(old_password):
            return False
        
        user.password = new_password
        db.session.commit()
        return True

    @staticmethod
    def update_login_info(user: User, login_ip: str) -> None:
        """
        更新用户登录信息
        :param user: 用户对象
        :param login_ip: 登录IP
        """
        from datetime import datetime
        user.last_login_time = datetime.utcnow()
        user.last_login_ip = login_ip
        db.session.commit() 

    @staticmethod
    def get_user_roles(user_id):
        """获取用户的所有角色"""
        try:
            from ..models.user_role import UserRole
            from ..models.role import Role
            
            user_roles = (Role.query
                         .join(UserRole, UserRole.role_id == Role.id)
                         .filter(UserRole.user_id == user_id)
                         .filter(Role.status == 1)  # 只获取启用的角色
                         .all())
            return user_roles
        except Exception as e:
            current_app.logger.error(f"获取用户角色失败: {str(e)}")
            return [] 